package db

import (
	"gitee.com/danlansky/go-library/repository/mysqldb"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

var (
	MysqlConnectMap = make(map[string]*mysqldb.MysqlDB)
)

type Mysql struct {
	Engine *gorm.DB
	Table  string
}

func NewMysql(name string, table string) *Mysql {
	if name == "" {
		defaultConnConfig := viper.GetString("database.default.name")
		return &Mysql{MysqlConnectMap[defaultConnConfig].Engine, table}
	}
	return &Mysql{MysqlConnectMap[name].Engine, table}
}

func Connection(name string) *gorm.DB {
	return MysqlConnectMap[name].Engine
}

func (m *Mysql) BeginTransaction() {
	tx := m.Engine.Clauses(dbresolver.Write).Begin()
	m.Engine = tx
}

func (m *Mysql) CommitTransaction() error {
	return m.Engine.Commit().Error
}

func (m *Mysql) RollbackTransaction() error {
	return m.Engine.Rollback().Error
}
